package com.rmiad.controller;

import org.noear.snack.ONode;
import org.noear.solon.Solon;
import org.noear.solon.Utils;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.util.ResourceUtil;
import org.noear.solon.hotplug.PluginInfo;
import org.noear.solon.hotplug.PluginManager;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;

import java.io.*;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class ConfigController {

    @Get
    @Mapping("/sys/config/init")
    public Result<Map<String, Object>> initConfig(String configFilename) throws IOException {
        File file = Utils.getFile(configFilename);
        if (!file.exists()) {
            URL url = ResourceUtil.findResourceOrFile(Solon.app().classLoader(), "classpath:" + configFilename);
            if (url == null) {
                List<PluginInfo> pluginInfoList = new ArrayList<>(PluginManager.getPlugins());
                for (int i = 0; i < pluginInfoList.size(); i++) {
                    url = ResourceUtil.findResourceOrFile(pluginInfoList.get(i).getAddinPackage().getClassLoader(),
                            "classpath:" + configFilename);
                }
            }
            String s = ResourceUtil.getResourceAsString(url);
            return Result.succeed(ONode.deserialize(s));
        }
        Yaml yaml = new Yaml();
        try (InputStream inputStream = new FileInputStream(file)) {
            Map<String, Object> config = yaml.load(inputStream);
            return Result.succeed(config);
        }
    }

    @Post
    @Mapping("/sys/config/update")
    public Result<Map<String, String>> updateConfig(Map<String, String> data, String configFilename) throws Throwable {
        Map<String, String> tempMap = new HashMap<>();
        data.forEach((key, value) -> {
            tempMap.put(key, ONode.deserialize(value));
        });

        File file = Utils.getFile(configFilename);
        if (!file.exists()) {
            // 创建文件
            file.createNewFile();
        }
        // 将 tempMap 转换为 YAML 格式
        DumperOptions options = new DumperOptions();
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
        options.setIndent(4);
        Yaml yaml = new Yaml(options);

        // 将 YAML 内容写入到文件中
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8))) {
            yaml.dump(tempMap, writer);
        }
        Solon.cfg().putAll(tempMap);
        return Result.succeed();
    }

}
